處理完getBootcamps controller的邏輯後(filtering, select, sort, pagination)
接著我們要建立另一組course的資料,並reference至Bootcamp model
這樣做的目的有兩個:
const mongoose = require('mongoose');
const CourseSchema = new mongoose.Schema({
title: {
type: String,
trim: true,
required: [true, 'Please add a course title']
},
description: {
type: String,
required: [true, 'Please add a description']
},
createdAt: {
type: Date,
default: Date.now
},
bootcamp: {
type: mongoose.Schema.ObjectId,
ref: 'Bootcamp',
required: true
}
});
module.exports = mongoose.model('Course', CourseSchema);
可以看到在schema的後面reference Bootcamp model
在controllers資料夾新增courses.js file
接著我們要處理兩個GET request
因此,當使用者有輸入bootcampId時,我們就能在courses資料庫中找到含有該id的courses資料
let query;
if (req.params.bootcampId) {
const bootcamp = await Bootcamp.findById(req.params.bootcampId);
if (!bootcamp) {
return next(
new ErrorResponse(`Bootcamp not found with id of ${req.params.bootcampId}`, 404)
);
} // 若輸入格式相同但錯誤的bootcampId, return error message
query = Course.find({ bootcamp: req.params.bootcampId });
} else {
query = Course.find();
}
const courses = await query;